import { ReactElement, useRef, useState, useEffect, useContext } from 'react'
import { Modal, Form, Select, FormInstance } from 'antd'
import { Context } from '../../../../context'
import Dic, { DictionaryItem } from '@js/dictionary'

const { Item } = Form
const { Option } = Select

interface Props {
  visible: boolean
  hide: () => void
}

function Main ({ visible, hide }: Props): ReactElement {
  const { updateCaseDetail, caseDetail } = useContext(Context)
  const formRef = useRef<FormInstance>(null)
  const [options, setOptions] = useState<DictionaryItem[]>([])
  useEffect(() => {
    const d = new Dic()
    d.init('结案类型')
      .then(() => {
        setOptions(d.getList('结案类型'))
      })
      .catch(e => console.error(e))
  }, [])
  useEffect(() => {
    const c = formRef.current
    if (visible && caseDetail !== null && c !== null) {
      c.setFieldsValue({ closure_type: caseDetail.closure_type })
    } else if (!visible && c !== null) {
      c.resetFields()
    }
  }, [caseDetail, formRef, visible])
  return (
    <Modal title='修改结案类型' visible={visible} onOk={() => formRef.current?.submit()} onCancel={hide} maskClosable>
      <Form ref={formRef} labelCol={{ flex: '80px' }} onFinish={d => updateCaseDetail(d)}>
        <Item name='closure_type' label='结案类型' rules={[{ required: true, message: '结案类型不能为空' }]}>
          <Select placeholder='请选择'>
            {options.map((li, i) => {
              return <Option key={i} value={li.value}>{li.title}</Option>
            })}
          </Select>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
